#include "ObjReader.h"

//	skip a line
void ObjReader::skipLine(istream& is)
{
    char next;
    is >> std::noskipws;
    while( (is >> next) && ('\n' != next) );
}

//	skip a comment line
bool ObjReader::skipCommentLine(istream& is)
{
    char next;
    while( is >> std::skipws >> next )
    {
        is.putback(next);
        if ('#' == next)
            skipLine(is);
        else
            return true;
    }
    return false;
}

bool ObjReader::processLine(istream& is)
{
    string ele_id;
    float x, y, z;

    if (!(is >> ele_id))
        return false;

    if ("v" == ele_id) {	//	vertex data
        is >> x >> y >> z;
        //pMesh->addVertex(SVertex(x, y, z));
    }
    else if ("vt" == ele_id) {	// texture data
        is >> x >> y >> z;
        is.clear();                           // is z (i.e. w) is not available, have to clear error flag.
        //pMesh->addTextureCoord(SVertex(x, y, z));
    }
    else if ("vn" == ele_id) {	// normal data
        is >> x >> y >> z;
        if(!is.good()) {                     // in case it is -1#IND00
            x = y = z = 0.0;
            is.clear();
            skipLine(is);
        }
        //pMesh->addNormal(SVertex(x, y, z));
    }
    else if ("f" == ele_id) {	//	face data
        //	face treatment
        //  Note: obviously this technique only works for convex polygons with ten verts or less.
        int vi[10];                               // vertex indices.
        int ni[10] = { -1, -1, -1, -1, };         // normal indices.
        int ti[10] = { -1, -1, -1, -1, };         // tex indices.
        int i = 0;
        for (char c; i<10; ++i) {
            if(true/*!pMesh->hasTextureCoords() && !pMesh->hasNormals()*/)
                is >> vi[i];
            else if(true/*!pMesh->hasTextureCoords()*/)
                is >> vi[i] >> c >> c >> ni[i];
            else if(true/*!pMesh->hasNormals()*/)
                is >> vi[i] >> c >> ti[i];
            else
                is >> vi[i] >> c >> ti[i] >> c >>  ni[i];

            if(!is.good())
                break;
        }
        //	Create the polygon face
        //SPolygonFace face;
        for (int k=0; k < i; ++k)
            //face.addVertTexNorm(vi[k], ti[k], ni[k]);
        //pMesh->addFace(face);

        is.clear();
    }
    else
        skipLine(is);
    return true;
}

void ObjReader::read(const string& strFileName)
{
    ifstream ifs(strFileName.c_str(), ios::in|ios::ate);
    if (!ifs) {
        // File not found throw(CFileNotFoundException(strFileName));
    }

    const int fileSize = ifs.tellg();
    ifs.seekg (0, ios::beg);

    if (0 == fileSize) {
        // File is empty;
    }

    while(skipCommentLine(ifs))
    {
        if (false == processLine(ifs)) {
            break;
        }
    }

    ifs.close();
}
